import { stringify } from 'querystring';
import { router } from 'umi';
import { getFakeCaptcha, accountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import {setToken} from "@/utils/token";
import { notification } from "antd";

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
    token: undefined
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully

      console.log(response);
      if (response.access_token) {
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        
        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            // redirect = redirect.substr((urlParams.origin +'/test/admin').length);
            redirect = redirect.substr(urlParams.origin.length);

            redirect = '/product'
            console.log('------------')
            console.log(redirect)
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            console.log(redirect)
            console.log('***************')
            window.location.href = redirect;
            return;
          }
        }
        // if(redirect.indexOf('/public/dist/public/dist') >-1) {
        //   redirect = redirect.substr('/public/dist'.length())
        // }
        router.replace(redirect || '/');
      }else{
        notification.error({
          description: '账号或密码错误',
          message: '登录失败',
        });
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },

    logout() {
      const { redirect } = getPageQuery(); // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
        router.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      setAuthority('admin');
      const issueTime = parseInt(new Date().getTime() / 1000);
      setToken({...payload,
        issueTime
      });
      return { ...state, status: true, token: payload.access_token};
    },
  },
};
export default Model;
